import { colorPrimary } from '@/config/theme'
import { useI18n } from '/@/hooks/web/useI18n'

/**
 * 获取授权登录的code
 */
export const getAuthCode = (): Promise<string> =>
  new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    weixinAuthService.authorize(
      function (res: { code: string }) {
        resolve(res.code)
      },
      function (err: any) {
        console.log(err)
        reject(new Error('微信登录失败'))
      },
    )
    // #endif
    // #ifdef MP
    uni.getProvider({
      service: 'oauth',
      success: (res) => {
        uni.login({
          provider: res.provider[0],
          success: (res: { code: string }) => {
            resolve(res.code)
          },
          fail(err: any) {
            console.log(err)
            reject(new Error('登录失败'))
          },
        } as any)
      },
    })

    // #endif
  })

/**
 * 发起抖音小程序支付请求 拉起外部支付
 * {service} 3 微信支付 4支付宝支付 5拉取抖音支付平台
 * {provider} alipay 支付宝 wxpay 微信
 * @param {Object} 参数
 */
export const ttPayment = (option: { payment: any; pay_type: number }) => {
  const options = {
    orderInfo: option.payment,
    service: 5,
    provider: option.pay_type === 30 ? 'alipay' : 'wxpay',
  }
  return new Promise((resolve, reject) => {
    tt.pay({
      provider: options.provider,
      orderInfo: options.orderInfo,
      service: options.service,
      success: (res: unknown) => resolve(res),
      fail: (res: any) => reject(res),
    })
  })
}

/**
 * 发起微信小程序支付请求
 * @param {Object} 参数
 */
export const wxPayment = ({ payment }: any) => {
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: payment.timeStamp,
      nonceStr: payment.nonceStr,
      package: payment.package,
      signType: 'MD5',
      paySign: payment.paySign,
      success: (res: unknown) => {
        console.log('res', res)
        resolve(res)
      },
      fail: (error: any) => {
        console.log('fail', error)
        reject(error)
      },
    } as any)
  })
}

/* 微信订阅消息 */
export const wxSubscribeMessage = (tmplIds: string[]) => {
  return new Promise((resolve, reject) => {
    uni.requestSubscribeMessage({
      tmplIds,
      success: () => resolve(true),
      fail: (err) => {
        console.error('wxSubscribeMessage Error:', err)
        // eslint-disable-next-line prefer-promise-reject-errors
        reject(false)
      },
    })
  })
}

/**
 * 小程序基础库 版本号 用于比较
 * @param {*} v1 :当前版本号
 * @param {*} v2：需要比较的版本号
 */
export const compareVersion = (curr: string, target: string): number => {
  const v1 = curr.split('.')
  const v2 = target.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }
  for (let i = 0; i < len; i += 1) {
    const num1 = Number(v1[i])
    const num2 = Number(v2[i])

    if (num1 > num2) {
      return 1
    }
    if (num1 < num2) {
      return -1
    }
  }

  return 0
}

/**
 * 返回上一页携带参数
 */
/**
 * 返回上一页携带参数
 */
export const prePage = (index = 2) => {
  const pages = getCurrentPages()
  const prePage = pages[pages.length - index]
  // #ifdef H5
  return prePage
  // #endif
}
/**
 * 保存网络照片到手机
 */
export const saveNetworkImg = (src: string) => {
  uni.getSetting({
    // eslint-disable-next-line consistent-return
    success: (res) => {
      if (res.authSetting['scope.writePhotosAlbum']) {
        return saveImg(src)
      }
      // 则设置进入页面时主动弹出，直接授权
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          saveImg(src)
        },
        fail() {
          uni.showModal({
            title: '是否授权存储信息',
            content: '需要获取将照片保存到相册',
            showCancel: false,
            success: (_) => {
              uni.openSetting({
                // 点击确定则调其用户设置
                success: (data) => {
                  if (data.authSetting['scope.writePhotosAlbum']) {
                    saveImg(src)
                  }
                },
              })
            },
          })
        },
      })
    },
    fail(err) {
      console.log(err)
    },
  })
}

/**
 * 小程序保存照片到相册
 */
export const saveImg = (src: string) => {
  uni.showLoading({
    title: '保存中',
    mask: true,
  })
  uni.downloadFile({
    url: src, // 网络图片的地址
    success: (res) =>
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath, // 临时文件地址
        success: () => {
          uni.showToast({
            title: '保存成功',
            icon: 'success',
          })
        },
        fail: () => {
          uni.showToast({
            title: '保存失败',
            icon: 'error',
          })
        },
        complete: () => uni.hideLoading(),
      }),
    fail: () => {
      uni.showToast({
        title: '保存失败外',
        icon: 'error',
      })
    },
  })
}

/** copy 内容复制 */
export const copy = (text: string) => {
  const { t } = useI18n()
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.$u.toast(t('common.copySuccess'))
    },
  })
}

/**
 * 模态参数请求封装
 * @param content 提示内容
 * @param api 接口请求
 * @param params 请求参数
 * @param callback 回调
 * @returns
 */
export const requestModdal = (
  content: string,
  api: (arg: any) => Promise<any>,
  params: Record<string, any>,
  callback: () => void,
) =>
  uni.showModal({
    title: '友情提示',
    confirmColor: colorPrimary,
    content,
    success: (res) => {
      if (res.confirm) {
        api &&
          api(params).then((res: any) => {
            uni.$u.toast(res.message)
            callback && callback()
          })
      }
    },
  })

/**
 * 获取节点高度
 */
export const getRect = (instance: any, selector: any, all = false) => {
  return new Promise((resolve) => {
    uni
      .createSelectorQuery()
      .in(instance)
      [all ? 'selectAll' : 'select'](selector)
      .boundingClientRect((rect) => {
        if (all && Array.isArray(rect) && rect.length) {
          resolve(rect)
        }
        if (!all && rect) {
          resolve(rect)
        }
      })
      .exec()
  })
}

// 本人项目中，已注入Vue原型链的$m，故下方代码通过this.$m.isWxBrowser()与this.$m.isIos()调用
export const isWxBrowser = () => {
  // 判断是否H5微信环境，true为微信浏览器
  const ua: any = navigator.userAgent.toLowerCase()
  return ua.match(/MicroMessenger/i) === 'micromessenger'
}

export const isIos = () => {
  // 是否IOS true为ios
  const u: any = navigator.userAgent
  const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  return !!isIOS
}

//微信浏览器中打开H5隐藏顶部导航方法
export const hidePageNavInWechatBrowser = () => {
  //#ifdef H5
  if (isWxBrowser()) {
    const pageNav: any = document.getElementsByTagName('uni-page-head')
    if (pageNav && pageNav[0]) {
      pageNav[0].style.display = 'none'
    }
  }
  //#endif
}
